package com.cloud.wms.ui.group.sampling;

import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.text.TextUtils;
import android.widget.TextView;

import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cloud.core.eventBus.Event;
import com.cloud.core.eventBus.EventBusUtil;
import com.cloud.core.utils.NumberUtils;
import com.cloud.widget.ScanText;
import com.cloud.wms.R;
import com.cloud.wms.base.BaseBarListActivity;
import com.cloud.wms.config.EventConfig;
import com.cloud.wms.config.IntentKey;
import com.cloud.wms.ui.group.contract.GroupSamplingContract;
import com.cloud.wms.ui.group.entity.SamplingCommodityEntity;
import com.cloud.wms.ui.group.presenter.GroupSamplingPresenter;
import com.cloud.wms.ui.main.entity.TaskEntity;
import com.cloud.wms.ui.sort.entity.BatchInfoEntity;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Author:Chen
 * @Date: 2021-03-10 16:16
 * @Description:
 */
public class SamplingConfirmActivity extends BaseBarListActivity<SamplingCommodityEntity, GroupSamplingPresenter> implements GroupSamplingContract.View {
    @BindView(R.id.scan_text)
    ScanText scanText;
    @BindView(R.id.tv_batch_code)
    TextView tvBatchCode;
    @BindView(R.id.tv_commodity_amount)
    TextView tvCommodityAmount;
    @BindView(R.id.tv_scan_amount)
    TextView tvScanAmount;
    @BindView(R.id.btn_confirm)
    TextView btnConfirm;
    private BatchInfoEntity batchInfoEntity;
    private TaskEntity taskEntity;
    private ArrayList<SamplingCommodityEntity> commodityList;
    private String needSamplingCount;
    private String carryCode;
    private int totalAmount;

    @Override
    protected String barTitle() {
        return "抽检确认";
    }

    @Override
    protected int getResId() {
        return R.layout.activity_group_sampling_confirm;
    }

    @Override
    protected int getItemResId() {
        return R.layout.item_group_sampling_confirm;
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        initScanText(scanText);
        taskEntity = getIntent().getParcelableExtra(IntentKey.TASK_KEY);
        needSamplingCount = getIntent().getStringExtra(IntentKey.INFO_KEY);
        carryCode = getIntent().getStringExtra(IntentKey.TYPE_KEY);
        batchInfoEntity = getIntent().getParcelableExtra(IntentKey.OBJECT_KEY);
        commodityList = getIntent().getParcelableArrayListExtra(IntentKey.LIST_KEY);

        tvBatchCode.setText(TextUtils.isEmpty(taskEntity.getMainBillCode()) ? taskEntity.getBillCode() : taskEntity.getMainBillCode());
        tvScanAmount.setText("0");
        mAdapter.setNewInstance(commodityList);
        for (int i = 0; i < commodityList.size(); i++) {
            totalAmount = totalAmount + commodityList.get(i).getAmount();
        }
        tvCommodityAmount.setText(String.valueOf(totalAmount));
    }

    @Override
    protected void onScanHandle(String result, int resultCode) {
        super.onScanHandle(result, resultCode);
        scanText.addHistory(result);
        if (isSamplingComplete()) {
            info("当前已抽检完成，请确认抽检！");
            btnConfirm.setEnabled(true);
            return;
        }
        int scanAmount = NumberUtils.getIntegerValue(tvScanAmount.getText().toString());
        for (int i = 0; i < commodityList.size(); i++) {
            SamplingCommodityEntity entity = commodityList.get(i);
            if (entity.getBarCode().equalsIgnoreCase(result)) {
                if (entity.getScanAmount() < entity.getAmount()) {
                    scanAmount++;
                    entity.setScanAmount(entity.getScanAmount() + 1);
                    tvScanAmount.setText(scanAmount + "");
                    success("抽检扫描成功！");
                    if (isSamplingComplete()) btnConfirm.setEnabled(true);
                } else {
                    info("当前扫描商品已抽检完成，请检查数量！");
                }
                return;
            }
        }
        info("扫描商品不再订单明细中，请检查！");
    }

    private boolean isSamplingComplete() {
        int scanAmount = NumberUtils.getIntegerValue(tvScanAmount.getText().toString());
        return !(totalAmount > scanAmount);
    }

    @Override
    protected void bindItemData(BaseViewHolder helper, SamplingCommodityEntity item) {
        helper.setText(R.id.tv_commodity_code, item.getBarCode())
                .setText(R.id.tv_commodity_name, item.getCommodityName())
                .setText(R.id.tv_commodity_amount, item.getAmount() + "");
    }

    @Override
    protected void setupComponent() {
        getActivityComponent().inject(this);
    }

    @Override
    public void onSuccess(Message message) {
        switch (message.what) {
            case GroupSamplingPresenter.SUBMIT_SAMPLING:
                success("抽检确认成功！");
                EventBusUtil.sendEvent(new Event<>(EventConfig.TASK_REFRESH));
                EventBusUtil.sendEvent(new Event<>(EventConfig.CLOSE_REFRESH));
                this.finish();
                break;
        }
    }

    @OnClick(R.id.btn_confirm)
    public void onViewClicked() {
        mPresenter.submitSampling(taskEntity == null ? batchInfoEntity.getBatchID() : taskEntity.getBillID(), taskEntity, needSamplingCount, carryCode);
    }

    public static void start(Context context, TaskEntity taskEntity, BatchInfoEntity batchInfoEntity, String needSamplingCount, String carryCode, ArrayList<SamplingCommodityEntity> commodityList) {
        Intent intent = new Intent(context, SamplingConfirmActivity.class);
        intent.putExtra(IntentKey.TASK_KEY, taskEntity);
        intent.putExtra(IntentKey.OBJECT_KEY, batchInfoEntity);
        intent.putExtra(IntentKey.LIST_KEY, commodityList);
        intent.putExtra(IntentKey.INFO_KEY, needSamplingCount);
        intent.putExtra(IntentKey.TYPE_KEY, carryCode);
        context.startActivity(intent);
    }
}
